package medOffice.Gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.StringTokenizer;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.ListModel;
import javax.swing.text.MaskFormatter;

import medOffice.Clinica;
import medOffice.Representante;
import medOffice.Verificador;

/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
/**
 * @author Ana Clara Lacerda - anacls@lcc.ufcg.edu.br
 * @version 0.1 - 03/12/2009
 * 
 */
public class RepresentanteGUI {

	private JPanel cadastra;
	private JPanel visualiza;
	private JTextArea jTextArea2;
	private JTextArea jTextArea;
	private JButton apagar;
	private JButton close;
	private JButton edit;
	private JList listaRep;
	private Clinica minhaClinica;
	private JLabel jLabel2;
	private JLabel jLabel3;
	private JLabel jLabel4;
	private JLabel jLabel5;
	private JTextArea jTextArea1;
	private JButton fechar;
	private JButton salvar;
	private JButton limpar;
	private JFormattedTextField jFormattedTextField1;
	private JLabel jLabel6;
	private JTextField dias;
	private JTextField firma;
	private JTextField nome;
	private JFormattedTextField telefone;
	private JLabel jLabel1;
	private JTabbedPane tabbed;

	public RepresentanteGUI(Clinica clinica, JTabbedPane tabbed) {
		minhaClinica = clinica;
		this.tabbed = tabbed;
	}

	private void panelCadastra(final Representante r) {
		cadastra = new JPanel();
		{
			jLabel1 = new JLabel();
			jLabel1.setText("*Nome:");
		}
		{
			jLabel4 = new JLabel();
			jLabel4.setText("*Tempo Limite entre visitas:");
		}
		{
			jLabel5 = new JLabel();
			jLabel5.setText("*Data da ultima Visita:");
		}
		{
			telefone = new JFormattedTextField(createFormatter("####-####"));
		}
		{
			jLabel2 = new JLabel();
			jLabel2.setText("*Firma Representada:");
		}
		{
			jLabel3 = new JLabel();
			jLabel3.setText("Telefone: ");
		}
		GroupLayout cadastraLayout = new GroupLayout((JComponent)cadastra);
		cadastra.setLayout(cadastraLayout);
		cadastraLayout.setVerticalGroup(cadastraLayout.createSequentialGroup()
			.addContainerGap(39, 39)
			.addComponent(getJTextArea(), GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
			.addGap(39)
			.addGroup(cadastraLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(getNome(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			    .addComponent(jLabel1, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 18, GroupLayout.PREFERRED_SIZE))
			.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
			.addGroup(cadastraLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(jLabel2, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
			    .addComponent(getJTextField1(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
			.addGap(20)
			.addGroup(cadastraLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(jLabel3, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
			    .addComponent(telefone, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
			.addGap(19)
			.addGroup(cadastraLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(jLabel4, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
			    .addComponent(getDias(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
			    .addComponent(getJLabel6(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 18, GroupLayout.PREFERRED_SIZE))
			.addGap(19)
			.addGroup(cadastraLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(jLabel5, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
			    .addComponent(getJFormattedTextField1(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
			.addGap(57)
			.addGroup(cadastraLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
			    .addComponent(getLimpar(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)
			    .addComponent(getSalvar(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 32, GroupLayout.PREFERRED_SIZE)
			    .addComponent(getFechar(), GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE))
			.addContainerGap(49, 49));
		cadastraLayout.setHorizontalGroup(cadastraLayout.createSequentialGroup()
			.addContainerGap()
			.addGroup(cadastraLayout.createParallelGroup()
			    .addGroup(cadastraLayout.createSequentialGroup()
			        .addGroup(cadastraLayout.createParallelGroup()
			            .addComponent(jLabel4, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
			            .addGroup(GroupLayout.Alignment.LEADING, cadastraLayout.createSequentialGroup()
			                .addComponent(jLabel5, GroupLayout.PREFERRED_SIZE, 142, GroupLayout.PREFERRED_SIZE)
			                .addGap(31))
			            .addGroup(GroupLayout.Alignment.LEADING, cadastraLayout.createSequentialGroup()
			                .addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 149, GroupLayout.PREFERRED_SIZE)
			                .addGap(24)))
			        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
			        .addGroup(cadastraLayout.createParallelGroup()
			            .addGroup(GroupLayout.Alignment.LEADING, cadastraLayout.createSequentialGroup()
			                .addComponent(getJFormattedTextField1(), GroupLayout.PREFERRED_SIZE, 78, GroupLayout.PREFERRED_SIZE)
			                .addGap(0, 121, Short.MAX_VALUE))
			            .addGroup(GroupLayout.Alignment.LEADING, cadastraLayout.createSequentialGroup()
			                .addComponent(getDias(), GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE)
			                .addComponent(getJLabel6(), GroupLayout.PREFERRED_SIZE, 154, GroupLayout.PREFERRED_SIZE)
			                .addGap(0, 0, Short.MAX_VALUE))
			            .addGroup(cadastraLayout.createSequentialGroup()
			                .addComponent(getJTextField1(), GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
			                .addGap(0, 0, Short.MAX_VALUE))))
			    .addGroup(GroupLayout.Alignment.LEADING, cadastraLayout.createSequentialGroup()
			        .addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE)
			        .addComponent(telefone, GroupLayout.PREFERRED_SIZE, 138, GroupLayout.PREFERRED_SIZE)
			        .addGap(0, 170, Short.MAX_VALUE))
			    .addGroup(GroupLayout.Alignment.LEADING, cadastraLayout.createSequentialGroup()
			        .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 58, GroupLayout.PREFERRED_SIZE)
			        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
			        .addComponent(getNome(), GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
			        .addGap(0, 115, Short.MAX_VALUE))
			    .addGroup(GroupLayout.Alignment.LEADING, cadastraLayout.createSequentialGroup()
			        .addGap(30)
			        .addComponent(getJTextArea(), GroupLayout.PREFERRED_SIZE, 216, GroupLayout.PREFERRED_SIZE)
			        .addGap(0, 138, Short.MAX_VALUE)))
			.addGap(0, 36, GroupLayout.PREFERRED_SIZE)
			.addComponent(getLimpar(), GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
			.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
			.addComponent(getSalvar(), GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
			.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
			.addComponent(getFechar(), GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)
			.addContainerGap(65, Short.MAX_VALUE));
		cadastra.setPreferredSize(new java.awt.Dimension(757, 431));
		cadastra.setBackground(new java.awt.Color(208, 228, 208));

		getFechar().addActionListener((new java.awt.event.ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				tabbed.remove(tabbed
						.indexOfTab("Cadastra/Edita Representantes"));
			}
		}));

		getLimpar().addActionListener((new java.awt.event.ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				nome.setText("");
				telefone.setText("");
				firma.setText("");
				dias.setText("");
				getJFormattedTextField1().setText("");
			}
		}));

		if (r == null) {
			getSalvar().addActionListener((new java.awt.event.ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {

					try {
						Representante repNovo = new Representante(nome
								.getText(), firma.getText());
						repNovo.setTelefone(telefone.getText());
						Integer dia = null;
						try {
							dia = Integer.valueOf(dias.getText());
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null,
									"Tempo limite invalido", "Atenção!",
									JOptionPane.PLAIN_MESSAGE);
						}
						repNovo.setTempoLimite(dia);
						Calendar dataUltima;
						if (!Verificador.verificaData(getJFormattedTextField1()
								.getText())) {
							throw new Exception("Data no formato errado");
						} else {
							Integer diaa = Integer
									.valueOf(getJFormattedTextField1()
											.getText().substring(0, 1));
							Integer mes = Integer
									.valueOf(getJFormattedTextField1()
											.getText().substring(3, 4)) - 1;
							Integer ano = Integer
									.valueOf(getJFormattedTextField1()
											.getText().substring(6, 9));
							dataUltima = new GregorianCalendar(ano, mes, diaa);
						}
						repNovo.setUltimaDataDeVisita(dataUltima);
						repNovo.setId(pegaMaiorId(minhaClinica
								.getListaRepresentantes()) + 1);
						minhaClinica.addRepresentante(repNovo);
						JOptionPane.showMessageDialog(null, "O representante "
								+ repNovo.getNome() + ", da firma "
								+ repNovo.getFirmaQueRepresenta()
								+ " foi adicionado com sucesso", "Sucesso",
								JOptionPane.PLAIN_MESSAGE);
						tabbed.remove(tabbed
								.indexOfTab("Cadastra/Edita Representantes"));
					} catch (Exception e) {
						JOptionPane.showMessageDialog(null, e.getMessage(),
								"Atenção!", JOptionPane.PLAIN_MESSAGE);
					}
				}
			}));
		} else {
			nome.setText(r.getNome());
			firma.setText(r.getFirmaQueRepresenta());
			telefone.setText(r.getTelefone());
			dias.setText(String.valueOf(r.getTempoLimite()));
			getJFormattedTextField1().setText(
					new SimpleDateFormat("dd/MM/yyyy").format(r
							.getUltimaDataDeVisita().getTime()));
			getSalvar().addActionListener((new java.awt.event.ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					try {
						r.setNome(nome.getText());
						r.setFirmaQueRepresenta(firma.getText());
						r.setTelefone(telefone.getText());
						Integer dia = null;
						try {
							dia = Integer.valueOf(dias.getText());
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null,
									"Tempo limite invalido", "Atenção!",
									JOptionPane.PLAIN_MESSAGE);
						}
						r.setTempoLimite(dia);
						Calendar dataUltima;
						if (!Verificador.verificaData(getJFormattedTextField1()
								.getText())) {
							throw new Exception("Data no formato errado");
						} else {
							Integer diaa = Integer
									.valueOf(getJFormattedTextField1()
											.getText().substring(0, 1));
							Integer mes = Integer
									.valueOf(getJFormattedTextField1()
											.getText().substring(3, 4)) - 1;
							Integer ano = Integer
									.valueOf(getJFormattedTextField1()
											.getText().substring(6, 9));
							dataUltima = new GregorianCalendar(ano, mes, diaa);
						}
						r.setUltimaDataDeVisita(dataUltima);
						minhaClinica.editaRepresentante(r.getId(), r);
						JOptionPane.showMessageDialog(null,
								"Os novos dados foram salvos", "Sucesso",
								JOptionPane.PLAIN_MESSAGE);
						tabbed.remove(tabbed
								.indexOfTab("Cadastra/Edita Representantes"));
					} catch (Exception e) {
						JOptionPane.showMessageDialog(null, e.getMessage(),
								"Atenção!", JOptionPane.PLAIN_MESSAGE);
					}
				}
			}));
		}

	}

	public JPanel getCadastra(Representante r) {
		if (cadastra == null)
			panelCadastra(r);
		return cadastra;
	}

	/**
	 * retirado de:
	 * <u>http://java.sun.com/docs/books/tutorial/uiswing/components
	 * /formattedtextfield.html</u>
	 */
	private MaskFormatter createFormatter(String s) {
		MaskFormatter formatter = null;
		try {
			formatter = new MaskFormatter(s);
			formatter.setPlaceholderCharacter('_');
		} catch (java.text.ParseException exc) {
			System.err.println("Formatacao invalida: " + exc.getMessage());
			System.exit(-1);
		}
		return formatter;
	}

	private JTextField getNome() {
		if (nome == null) {
			nome = new JTextField();
		}
		return nome;
	}

	private JTextField getJTextField1() {
		if (firma == null) {
			firma = new JTextField();
		}
		return firma;
	}

	private JTextField getDias() {
		if (dias == null) {
			dias = new JTextField();
		}
		return dias;
	}

	private JLabel getJLabel6() {
		if (jLabel6 == null) {
			jLabel6 = new JLabel();
			jLabel6.setText("(numero de dias)");
		}
		return jLabel6;
	}

	private JFormattedTextField getJFormattedTextField1() {
		if (jFormattedTextField1 == null) {
			jFormattedTextField1 = new JFormattedTextField(
					createFormatter("##/##/####"));
		}
		return jFormattedTextField1;
	}

	private JButton getLimpar() {
		if (limpar == null) {
			limpar = new JButton();
			limpar.setText("Limpar");
			limpar.setBackground(new java.awt.Color(75, 95, 75));
			limpar.setForeground(new java.awt.Color(144, 238, 144));
		}
		return limpar;
	}

	private JButton getSalvar() {
		if (salvar == null) {
			salvar = new JButton();
			salvar.setText("Salvar");
			salvar.setBackground(new java.awt.Color(75, 95, 75));
			salvar.setForeground(new java.awt.Color(144, 238, 144));
		}
		return salvar;
	}

	private JButton getFechar() {
		if (fechar == null) {
			fechar = new JButton();
			fechar.setText("Fechar");
			fechar.setBackground(new java.awt.Color(75, 95, 75));
			fechar.setForeground(new java.awt.Color(144, 238, 144));
		}
		return fechar;
	}

	private int pegaMaiorId(List<Representante> lista) {
		if (lista.isEmpty()) {
			return 1;
		}
		List<Integer> inteiros = new ArrayList<Integer>();
		for (Representante rep : lista) {
			inteiros.add(rep.getId());
		}

		int maior = inteiros.get(0);
		for (Integer integer : inteiros) {
			if (integer > maior)
				maior = integer;
		}
		return maior;
	}

	private JTextArea getJTextArea() {
		if (jTextArea == null) {
			jTextArea = new JTextArea();
			jTextArea.setText("Dados do Representante");
			jTextArea.setEditable(false);
			jTextArea.setForeground(new java.awt.Color(26, 101, 26));
			jTextArea.setOpaque(false);
			jTextArea.setFont(new java.awt.Font("Purisa", 1, 14));
		}
		return jTextArea;
	}

	public JPanel getVisualiza() {
		if (visualiza == null)
			panelVisualiza();
		return visualiza;
	}

	private void panelVisualiza() {
		visualiza = new JPanel();

		visualiza.setLayout(null);
		visualiza.add(getJTextArea1());
		visualiza.add(getListaRep());
		visualiza.add(getEdit());
		visualiza.add(getApagar());
		visualiza.add(getClose());
		visualiza.setBackground(new java.awt.Color(208, 228, 208));
		visualiza.setPreferredSize(new java.awt.Dimension(751, 430));
		visualiza.setEnabled(true);

		getEdit().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String s = (String) listaRep.getSelectedValue();
				if (s == null ) {
					JOptionPane.showMessageDialog(null,"Nenhuma representante foi selecionado",
							"Atencao", JOptionPane.PLAIN_MESSAGE);
				} else {
				StringTokenizer st = new StringTokenizer(s, "|");
				String nome = st.nextToken().substring(15).trim();
				Representante editavel = null;
				try {
					for (Representante r : minhaClinica
							.getListaRepresentantes()) {
						if (r.getNome().equals(nome))
							editavel = r;
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				tabbed.addTab("Cadastra/Edita Representantes", null,
						getCadastra(editavel), null);

			}
			}
		});
		getClose().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				tabbed.remove(tabbed.indexOfTab("Representantes"));

			}
		});

		getApagar().addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String s = (String) listaRep.getSelectedValue();				
				StringTokenizer st = new StringTokenizer(s, "|");
				String nome = st.nextToken().substring(15).trim();
				Representante apagavel = null;
				try {
					for (Representante r : minhaClinica
							.getListaRepresentantes()) {
						if (r.getNome().equals(nome))
							apagavel = r;
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					minhaClinica.removeRepresentante(apagavel.getNome(),
							apagavel.getId());
					tabbed.remove(tabbed.indexOfTab("Representantes"));
				} catch (SQLException e1) {
					JOptionPane.showMessageDialog(null, e1.getMessage(),
							"Atencao", JOptionPane.PLAIN_MESSAGE);
				}
			}
		});
		
	}

	private JList getListaRep() {
		String[] strings = null;
		try {
			strings = new String[minhaClinica.getListaRepresentantes().size()];
		} catch (SQLException e) {
			e.printStackTrace();
		}
		for (int i = 0; i<strings.length; i++) {
			try {
				strings[i] = minhaClinica.getListaRepresentantes().get(i).toString();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		ListModel listaRepModel = new DefaultComboBoxModel(strings);
		listaRep = new JList();
		listaRep.setModel(listaRepModel);
		listaRep.setOpaque(false);
		listaRep.setSelectionBackground(new java.awt.Color(33, 92, 33));
		listaRep.setSelectionForeground(new java.awt.Color(170, 240, 170));
		listaRep.setBorder(BorderFactory.createTitledBorder(""));
		listaRep.setBounds(64, 106, 261, 260);

		return listaRep;
	}

	private JButton getClose() {
		if (close == null) {
			close = new JButton();
			close.setText("Fechar");
			close.setBackground(new java.awt.Color(75, 95, 75));
			close.setForeground(new java.awt.Color(144, 238, 144));
			close.setBounds(506, 200, 95, 34);
		}
		return close;
	}

	private JButton getEdit() {
		if (edit == null) {
			edit = new JButton();
			edit.setText("Editar");
			edit.setBackground(new java.awt.Color(75, 95, 75));
			edit.setForeground(new java.awt.Color(144, 238, 144));
			edit.setBounds(506, 330, 95, 34);
		}
		return edit;
	}

	private JButton getApagar() {
		if (apagar == null) {
			apagar = new JButton();
			apagar.setText("Remover");
			apagar.setBackground(new java.awt.Color(75, 95, 75));
			apagar.setForeground(new java.awt.Color(144, 238, 144));
			apagar.setBounds(506, 280, 95, 34);
		}
		return apagar;
	}

	private JTextArea getJTextArea1() {
		if (jTextArea1 == null) {
			jTextArea1 = new JTextArea();
			jTextArea1.setText("Relatorios Cadastrados");
			jTextArea1.setEditable(false);
			jTextArea1.setFont(new java.awt.Font("Purisa", 1, 14));
			jTextArea1.setOpaque(false);
			jTextArea1.setForeground(new java.awt.Color(26, 79, 26));
			jTextArea1.setBounds(42, 39, 298, 36);
		}
		return jTextArea1;
	}

	private JTextArea getJTextArea2() {
		if (jTextArea2 == null) {
			jTextArea2 = new JTextArea();
			jTextArea2
					.setText("Estes sao os Representantes que\nestao cadastrados na Clinica no\nmomento.\n'Editar' - edita os dados;\n'Remover' - remove da Clinica;\n");
			jTextArea2.setOpaque(false);
			jTextArea2.setFont(new java.awt.Font("Monospaced", 0, 11));
			jTextArea2.setForeground(new java.awt.Color(23, 53, 23));
		}
		return jTextArea2;
	}

}
